package com.data.dev.common.exception;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;

/**
 * 2022年6月17日15:10:38
 * @author wangxiaoming-ghq 2022-05-15
 * 该项目异常的基类，统一异常处理
 */
public class AlarmException   extends RuntimeException implements Serializable {

    private static final long serialVersionUID = 1L;

    public AlarmException(ErrorCode errorCode, String errorMessage)
    {
        super(errorCode.toString() + " - " + errorMessage);
    }

    private AlarmException(ErrorCode errorCode, String errorMessage, Throwable cause)
    {
        super(errorCode.toString() + " - " + getMessage(errorMessage) + " - " + getMessage(cause), cause);

    }
 
    public static AlarmException asAlarmException(ErrorCode errorCode, String message)
    {
        return new AlarmException(errorCode, message);
    }

    public static AlarmException asAlarmException(ErrorCode errorCode, Throwable cause)
    {
        if (cause instanceof AlarmException) {
            return (AlarmException) cause;
        }
        return new AlarmException(errorCode, getMessage(cause), cause);
    }

    private static String getMessage(Object obj)
    {
        if (obj == null) {
            return "";
        }

        if (obj instanceof Throwable) {
            StringWriter str = new StringWriter();
            PrintWriter pw = new PrintWriter(str);
            ((Throwable) obj).printStackTrace(pw);
            return str.toString();
        }
        else {
            return obj.toString();
        }
    }

}
